#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "libmodbus/modbus.h"
#include "comtcp.h"
#include <QSerialPortInfo>
#include <QSettings>

ComTcp *tcpcom;
uint16_t database[200];
ComTcp::ComMode  workmode;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        allports<<info.portName();
    }
    ui->comboBox->clear();
    ui->comboBox->addItems(allports);

    QSettings setting("RTU2TCPcfg.ini",QSettings::IniFormat);
    setting.beginGroup("SerialConfig");
    ui->comboBox->setCurrentIndex(ui->comboBox->findText(setting.value("SerialName").toString()));
    ui->SP_SerialID->setValue(setting.value("SerialID").toInt());
    ui->LE_IPADDR->setText(setting.value("TCPIPADDR","").toString());
    ui->LE_PORT->setText(setting.value("TCPPORT","").toString());
    ui->SP_TCPADDR->setValue(setting.value("TCPADDR").toInt());
    workmode=(ComTcp::ComMode)setting.value("WORKMODE").toInt();
    if(workmode==ComTcp::mode_in)
        ui->rd_in->setChecked(true);
    else
        ui->rd_out->setChecked(true);
    setting.endGroup();


}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_2_clicked()
{
    QSettings setting("RTU2TCPcfg.ini",QSettings::IniFormat);
    setting.beginGroup("SerialConfig");
    setting.setValue("SerialName",ui->comboBox->currentText());
    setting.setValue("SerialID",ui->SP_SerialID->value());
    setting.setValue("TCPIPADDR",ui->LE_IPADDR->text());
    setting.setValue("TCPPORT",ui->LE_PORT->text());
    setting.setValue("TCPADDR",ui->SP_TCPADDR->value());
    if(ui->rd_in->isChecked())
        workmode=ComTcp::mode_in;
    else
        workmode=ComTcp::mode_out;
    setting.setValue("WORKMODE",workmode);
    setting.endGroup();

}

void MainWindow::on_pushButton_clicked()
{
    QString getip=ui->LE_IPADDR->text();
    if(getip!="")
    {
        tcpcom=new ComTcp(ui->LE_IPADDR->text(),ui->LE_PORT->text().toInt(),database,ui->comboBox->currentText(),ui->SP_SerialID->value(),workmode);
        tcpcom->start();
    }
}
